import tkinter as tk  
from tkinter import messagebox, Toplevel, Entry, StringVar, Button  
import json  
  
def load_tasks():  
    # 尝试打开并加载任务文件
    try:  
        # 打开任务文件
        with open('tasks.json', 'r') as file:  
            # 从文件中加载任务数据
            tasks = json.load(file)  
    # 如果文件未找到
    except FileNotFoundError:  
        # 设置任务列表为空
        tasks = []  
    # 如果JSON解码出错
    except json.JSONDecodeError:  
        # 设置任务列表为空
        tasks = []  
    # 返回任务列表
    return tasks  
  
def save_tasks(tasks):  
    # 打开文件'tasks.json'以写入模式
    with open('tasks.json', 'w') as file:  
        # 将tasks列表以json格式写入文件，并设置缩进为4
        json.dump(tasks, file, indent=4)  
  
def add_task_window():  
    def on_add():
        # 获取输入框中的任务描述
        task_description = task_entry.get()

        # 检查任务描述是否为空
        if task_description:
            # 创建一个包含任务描述和完成状态的新任务
            task = {'description': task_description, 'completed': False}

            # 使用全局变量访问任务列表
            global tasks  # Use global variable to access tasks list

            # 将新任务添加到任务列表中
            tasks.append(task)

            # 保存任务列表
            save_tasks(tasks)

            # 更新任务列表显示
            update_task_list()

            # 关闭添加任务窗口
            add_task_top.destroy()  # Close the add task window

        else:
            # 如果任务描述为空，则显示警告消息
            messagebox.showwarning("Warning", "Task description cannot be empty!")  
  
    # Create a new toplevel window for adding a task  
    add_task_top = Toplevel(root)
    add_task_top.title("Add Task")
  
    task_entry_var = StringVar()
    task_entry = Entry(add_task_top, textvariable=task_entry_var, width=50)  
    task_entry.pack(padx=10, pady=10)  
  
    add_button = Button(add_task_top, text="Add", command=on_add)  
    add_button.pack(padx=10, pady=10)  
  
def update_task_list():  
    # 清空任务列表框
    task_listbox.delete(0, tk.END)  

    # 遍历任务列表
    for task in tasks:  
        # 根据任务是否完成设置状态标记
        status = "✓" if task['completed'] else "✗"  
        # 将任务状态和描述添加到任务列表框中
        task_listbox.insert(tk.END, f"{status} {task['description']}")  
  
def complete_task():  
    try:  
        selected_index = task_listbox.curselection()[0]  
        tasks[selected_index]['completed'] = True  
        save_tasks(tasks)  
        update_task_list()  
    except IndexError:  
        messagebox.showwarning("Warning", "No task selected!")  
  
def delete_task():  
    try:  
        selected_index = task_listbox.curselection()[0]  
        del tasks[selected_index]  
        save_tasks(tasks)  
        update_task_list()  
    except IndexError:  
        messagebox.showwarning("Warning", "No task selected!")  
  
# Initialize the application  
root = tk.Tk()  
root.title("ToDo List")  
  
# Create global tasks list  
tasks = load_tasks()  
  
# Create widgets  
task_listbox = tk.Listbox(root, width=50, height=10)  
task_listbox.grid(row=0, column=0, columnspan=3, padx=10, pady=10)  
  
add_button = tk.Button(root, text="Add Task", command=add_task_window)  
add_button.grid(row=1, column=0, columnspan=3, padx=10, pady=10)  
  
complete_button = tk.Button(root, text="Complete", command=complete_task)  
complete_button.grid(row=2, column=0, padx=10, pady=10)  
  
delete_button = tk.Button(root, text="Delete", command=delete_task)  
delete_button.grid(row=2, column=1, padx=10, pady=10)  
  
# Update task list initially  
update_task_list()  
  
# Run the application  
root.mainloop()